package com.sardine.base.threads.master;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 北京京东世纪贸易有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2015/11/27
 * Time:12:47
 *
 * @author daifeng<br>
 *         daifeng@jd.com
 * @since JDK 1.6 <br>
 * Copyright (c) 2015 JD System Incorporated All Rights Reserved.
 */
public abstract class MWorkerCollection extends MWorker{
    //多线程处理时，数组的步长；
    protected final int intCollectionSize;

    public MWorkerCollection(int collectionSize) {
        this.intCollectionSize=collectionSize;
    }

    @Override
    public void run() {

        while (true) {
            //得到执行的任务集合
            List<Object> input =getWorkerObj();
            if (input.size()==0) break;
            try {
                //处理子任务
                Object re = handle(input);
                if (re != null) {
                    if(re instanceof Collection){
                        List values=(List)re;
                        for (Object value : values) {
                            if(value!=null) resultMap.put(Integer.toString(value.hashCode()), value);
                        }
                    }else
                    {
                        resultMap.put(Integer.toString(re.hashCode()), re);
                    }
                }
            } finally {
                for (Object o : input) {
                    //结束线程
                    downLatch.countDown();
                }
            }
        }
    }

    /**
     * 得到执行的任务集合
     * @return
     */
    private List<Object> getWorkerObj(){
        List<Object> array=new ArrayList<Object>(intCollectionSize);
        for (int i = 0; i < intCollectionSize; i++) {
            //弹出一个任务
            Object input = workerQueue.poll();
            if (input == null) break;
            array.add(input);
        }
        return Collections.unmodifiableList(array);
    }
}
